#!/usr/bin/env python3
"""
RedFire 微服务创建工具
====================

基于模板快速创建新的微服务
"""

import os
import sys
import argparse
from pathlib import Path
from typing import Dict, List, Optional


class ServiceCreator:
    """微服务创建器"""
    
    def __init__(self, service_name: str, service_type: str = "api"):
        self.service_name = service_name
        self.service_type = service_type
        self.service_class = self._to_class_name(service_name)
        self.service_title = self._to_title(service_name)
        self.project_root = Path(__file__).parent.parent.parent
        
    def _to_class_name(self, name: str) -> str:
        """转换为类名"""
        return ''.join(word.capitalize() for word in name.split('-'))
    
    def _to_title(self, name: str) -> str:
        """转换为标题"""
        return ' '.join(word.capitalize() for word in name.split('-'))
    
    def create_service(self):
        """创建完整的微服务"""
        service_dir = self.project_root / "services" / self.service_name
        
        # 检查服务是否已存在
        if service_dir.exists():
            print(f"❌ 服务已存在: {service_dir}")
            return False
        
        print(f"🚀 创建微服务: {self.service_name}")
        
        # 创建目录结构
        self._create_directory_structure(service_dir)
        
        # 创建文件
        self._create_main_file(service_dir)
        self._create_dockerfile(service_dir)
        self._create_requirements(service_dir)
        self._create_api_files(service_dir)
        self._create_model_files(service_dir)
        self._create_schema_files(service_dir)
        self._create_service_files(service_dir)
        self._create_readme(service_dir)
        
        print(f"✅ 微服务 '{self.service_name}' 创建成功!")
        print(f"📁 位置: {service_dir}")
        print(f"🚀 启动命令: cd {service_dir} && python app/main.py")
        
        # 提示后续步骤
        self._show_next_steps()
        
        return True
    
    def _create_directory_structure(self, service_dir: Path):
        """创建目录结构"""
        directories = [
            "app",
            "app/api",
            "app/core",
            "app/models",
            "app/schemas",
            "app/services",
            "logs",
            "tests",
            "tests/unit",
            "tests/integration"
        ]
        
        for directory in directories:
            dir_path = service_dir / directory
            dir_path.mkdir(parents=True, exist_ok=True)
            
            # 创建__init__.py文件
            if directory.startswith("app") or directory.startswith("tests"):
                init_file = dir_path / "__init__.py"
                init_file.write_text('"""{}"""\n'.format(
                    directory.replace("app/", "").replace("app", "应用核心").title()
                ))
    
    def _create_main_file(self, service_dir: Path):
        """创建主应用文件"""
        main_content = f'''"""
{self.service_title}服务主应用
{'=' * (len(self.service_title) * 3 + 8)}

基于RedFire统一服务基类的{self.service_title}微服务
"""

import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from shared.core.service_base import RedFireAPIServiceBase
from shared.core.dependencies import get_service_dependencies
from .api.routes import router as api_router


class {self.service_class}Service(RedFireAPIServiceBase):
    """{self.service_title}服务类"""
    
    def __init__(self):
        super().__init__("{self.service_name}", "1.0.0")
        self.dependencies = get_service_dependencies("{self.service_name}")
    
    def setup_routes(self) -> None:
        """设置路由"""
        self.include_router(api_router, prefix="", tags=["{self.service_name}"])
        
        # 添加根路径
        @self.app.get("/")
        async def root():
            """根路径信息"""
            return {{
                "service": "RedFire {self.service_title}服务",
                "version": self.version,
                "description": "{self.service_title}微服务",
                "endpoints": {{
                    "health": "/health",
                    "docs": "/docs",
                    "redoc": "/redoc",
                    "api": self.api_prefix
                }}
            }}
    
    async def on_startup(self) -> None:
        """启动时的初始化"""
        await super().on_startup()
        self.logger.info("{self.service_title}服务初始化完成")
        
        # 这里可以添加服务特定的初始化逻辑
        try:
            # 初始化数据库连接
            from shared.database.unified_database import setup_databases
            await setup_databases(self.config)
            self.logger.info("数据库连接已建立")
        except Exception as e:
            self.logger.warning(f"数据库初始化失败: {{e}}")
    
    async def on_shutdown(self) -> None:
        """关闭时的清理"""
        await super().on_shutdown()
        await self.dependencies.cleanup()
        
        # 清理数据库连接
        try:
            from shared.database.unified_database import db_manager
            await db_manager.close_all()
            self.logger.info("数据库连接已关闭")
        except Exception as e:
            self.logger.warning(f"数据库清理失败: {{e}}")
        
        self.logger.info("{self.service_title}服务清理完成")
    
    async def check_health(self):
        """健康检查"""
        health_checks = {{
            "service": True,
            "database": False,
            "cache": False
        }}
        
        try:
            # 检查数据库连接
            from shared.database.unified_database import database_health_check
            db_health = await database_health_check()
            health_checks["database"] = db_health.get("healthy", False)
        except Exception as e:
            self.logger.error(f"数据库健康检查失败: {{e}}")
        
        try:
            # 检查Redis连接
            redis_client = await self.dependencies.get_redis()
            await redis_client.ping()
            health_checks["cache"] = True
        except Exception as e:
            self.logger.error(f"缓存健康检查失败: {{e}}")
        
        return {{
            "healthy": all(health_checks.values()),
            "checks": health_checks
        }}


# 服务启动入口
if __name__ == "__main__":
    service = {self.service_class}Service()
    service.run()
'''
        
        main_file = service_dir / "app" / "main.py"
        main_file.write_text(main_content)
    
    def _create_api_files(self, service_dir: Path):
        """创建API文件"""
        routes_content = f'''"""
{self.service_title}服务API路由
{'=' * (len(self.service_title) * 3 + 11)}
"""

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional

from shared.core.dependencies import get_database, get_current_user, get_logger
from ..schemas.requests import Create{self.service_class}Request, Update{self.service_class}Request
from ..schemas.responses import {self.service_class}Response, {self.service_class}ListResponse
from ..services.{self.service_name.replace('-', '_')}_service import {self.service_class}BusinessService

router = APIRouter()

# 获取依赖
get_db = get_database("{self.service_name}")
get_user = get_current_user("{self.service_name}")
logger = get_logger("{self.service_name}", "api")


@router.get("/", response_model={self.service_class}ListResponse)
async def list_items(
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_user)
):
    """获取{self.service_title}列表"""
    try:
        service = {self.service_class}BusinessService(db)
        items = await service.get_list(skip=skip, limit=limit)
        total = await service.get_count()
        
        return {self.service_class}ListResponse(
            items=[{self.service_class}Response.from_orm(item) for item in items],
            total=total,
            skip=skip,
            limit=limit
        )
    except Exception as e:
        logger.error(f"获取{self.service_title}列表失败: {{e}}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve items"
        )


@router.post("/", response_model={self.service_class}Response)
async def create_item(
    request: Create{self.service_class}Request,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_user)
):
    """创建{self.service_title}"""
    try:
        service = {self.service_class}BusinessService(db)
        item = await service.create(request, current_user["user_id"])
        return {self.service_class}Response.from_orm(item)
    except Exception as e:
        logger.error(f"创建{self.service_title}失败: {{e}}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to create item"
        )


@router.get("/{{item_id}}", response_model={self.service_class}Response)
async def get_item(
    item_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_user)
):
    """获取{self.service_title}详情"""
    try:
        service = {self.service_class}BusinessService(db)
        item = await service.get_by_id(item_id)
        if not item:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Item not found"
            )
        return {self.service_class}Response.from_orm(item)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取{self.service_title}详情失败: {{e}}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve item"
        )


@router.put("/{{item_id}}", response_model={self.service_class}Response)
async def update_item(
    item_id: int,
    request: Update{self.service_class}Request,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_user)
):
    """更新{self.service_title}"""
    try:
        service = {self.service_class}BusinessService(db)
        item = await service.update(item_id, request, current_user["user_id"])
        if not item:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Item not found"
            )
        return {self.service_class}Response.from_orm(item)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新{self.service_title}失败: {{e}}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to update item"
        )


@router.delete("/{{item_id}}")
async def delete_item(
    item_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_user)
):
    """删除{self.service_title}"""
    try:
        service = {self.service_class}BusinessService(db)
        success = await service.delete(item_id, current_user["user_id"])
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Item not found"
            )
        return {{"message": "Item deleted successfully"}}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除{self.service_title}失败: {{e}}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to delete item"
        )
'''
        
        routes_file = service_dir / "app" / "api" / "routes.py"
        routes_file.write_text(routes_content)
    
    def _create_model_files(self, service_dir: Path):
        """创建模型文件"""
        models_content = f'''"""
{self.service_title}服务数据模型
{'=' * (len(self.service_title) * 3 + 12)}
"""

from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime

Base = declarative_base()


class {self.service_class}Model(Base):
    """{self.service_title}模型"""
    
    __tablename__ = "{self.service_name.replace('-', '_')}"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255), nullable=False, index=True)
    description = Column(Text, nullable=True)
    status = Column(String(50), default="active", index=True)
    is_active = Column(Boolean, default=True, nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    created_by = Column(String(100), nullable=False)
    updated_by = Column(String(100), nullable=True)
    
    def __repr__(self):
        return f"<{self.service_class}Model(id={{self.id}}, name='{{self.name}}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {{
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "status": self.status,
            "is_active": self.is_active,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "created_by": self.created_by,
            "updated_by": self.updated_by
        }}
'''
        
        models_file = service_dir / "app" / "models" / f"{self.service_name.replace('-', '_')}.py"
        models_file.write_text(models_content)
    
    def _create_schema_files(self, service_dir: Path):
        """创建模式文件"""
        # 请求模式
        requests_content = f'''"""
{self.service_title}服务请求模式
{'=' * (len(self.service_title) * 3 + 12)}
"""

from pydantic import BaseModel, Field
from typing import Optional


class Create{self.service_class}Request(BaseModel):
    """创建{self.service_title}请求"""
    
    name: str = Field(..., min_length=1, max_length=255, description="名称")
    description: Optional[str] = Field(None, max_length=1000, description="描述")
    
    class Config:
        schema_extra = {{
            "example": {{
                "name": "示例{self.service_title}",
                "description": "这是一个示例{self.service_title}"
            }}
        }}


class Update{self.service_class}Request(BaseModel):
    """更新{self.service_title}请求"""
    
    name: Optional[str] = Field(None, min_length=1, max_length=255, description="名称")
    description: Optional[str] = Field(None, max_length=1000, description="描述")
    status: Optional[str] = Field(None, description="状态")
    is_active: Optional[bool] = Field(None, description="是否激活")
    
    class Config:
        schema_extra = {{
            "example": {{
                "name": "更新的{self.service_title}",
                "description": "更新后的描述",
                "status": "active",
                "is_active": True
            }}
        }}
'''
        
        requests_file = service_dir / "app" / "schemas" / "requests.py"
        requests_file.write_text(requests_content)
        
        # 响应模式
        responses_content = f'''"""
{self.service_title}服务响应模式
{'=' * (len(self.service_title) * 3 + 12)}
"""

from pydantic import BaseModel, Field
from datetime import datetime
from typing import List, Optional


class {self.service_class}Response(BaseModel):
    """{self.service_title}响应"""
    
    id: int = Field(..., description="ID")
    name: str = Field(..., description="名称")
    description: Optional[str] = Field(None, description="描述")
    status: str = Field(..., description="状态")
    is_active: bool = Field(..., description="是否激活")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    created_by: str = Field(..., description="创建者")
    updated_by: Optional[str] = Field(None, description="更新者")
    
    class Config:
        from_attributes = True
        schema_extra = {{
            "example": {{
                "id": 1,
                "name": "示例{self.service_title}",
                "description": "这是一个示例{self.service_title}",
                "status": "active",
                "is_active": True,
                "created_at": "2023-01-01T00:00:00",
                "updated_at": "2023-01-01T00:00:00",
                "created_by": "user123",
                "updated_by": "user123"
            }}
        }}


class {self.service_class}ListResponse(BaseModel):
    """{self.service_title}列表响应"""
    
    items: List[{self.service_class}Response] = Field(..., description="列表项")
    total: int = Field(..., description="总数")
    skip: int = Field(..., description="跳过数量")
    limit: int = Field(..., description="限制数量")
    
    class Config:
        schema_extra = {{
            "example": {{
                "items": [],
                "total": 0,
                "skip": 0,
                "limit": 100
            }}
        }}
'''
        
        responses_file = service_dir / "app" / "schemas" / "responses.py"
        responses_file.write_text(responses_content)
    
    def _create_service_files(self, service_dir: Path):
        """创建业务服务文件"""
        service_content = f'''"""
{self.service_title}业务服务
{'=' * (len(self.service_title) * 3 + 8)}
"""

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from typing import List, Optional

from ..models.{self.service_name.replace('-', '_')} import {self.service_class}Model
from ..schemas.requests import Create{self.service_class}Request, Update{self.service_class}Request


class {self.service_class}BusinessService:
    """{self.service_title}业务服务"""
    
    def __init__(self, db: AsyncSession):
        self.db = db
    
    async def get_list(self, skip: int = 0, limit: int = 100) -> List[{self.service_class}Model]:
        """获取列表"""
        stmt = (
            select({self.service_class}Model)
            .where({self.service_class}Model.is_active == True)
            .offset(skip)
            .limit(limit)
            .order_by({self.service_class}Model.created_at.desc())
        )
        result = await self.db.execute(stmt)
        return result.scalars().all()
    
    async def get_count(self) -> int:
        """获取总数"""
        stmt = (
            select(func.count({self.service_class}Model.id))
            .where({self.service_class}Model.is_active == True)
        )
        result = await self.db.execute(stmt)
        return result.scalar() or 0
    
    async def get_by_id(self, item_id: int) -> Optional[{self.service_class}Model]:
        """根据ID获取"""
        stmt = (
            select({self.service_class}Model)
            .where(
                {self.service_class}Model.id == item_id,
                {self.service_class}Model.is_active == True
            )
        )
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()
    
    async def create(self, request: Create{self.service_class}Request, user_id: str) -> {self.service_class}Model:
        """创建"""
        item = {self.service_class}Model(
            name=request.name,
            description=request.description,
            created_by=user_id,
            updated_by=user_id
        )
        
        self.db.add(item)
        await self.db.commit()
        await self.db.refresh(item)
        return item
    
    async def update(
        self, 
        item_id: int, 
        request: Update{self.service_class}Request, 
        user_id: str
    ) -> Optional[{self.service_class}Model]:
        """更新"""
        item = await self.get_by_id(item_id)
        if not item:
            return None
        
        # 更新字段
        update_data = request.dict(exclude_unset=True)
        for field, value in update_data.items():
            if hasattr(item, field):
                setattr(item, field, value)
        
        item.updated_by = user_id
        
        await self.db.commit()
        await self.db.refresh(item)
        return item
    
    async def delete(self, item_id: int, user_id: str) -> bool:
        """软删除"""
        item = await self.get_by_id(item_id)
        if not item:
            return False
        
        # 软删除
        item.is_active = False
        item.updated_by = user_id
        
        await self.db.commit()
        return True
    
    async def hard_delete(self, item_id: int) -> bool:
        """硬删除"""
        item = await self.get_by_id(item_id)
        if not item:
            return False
        
        await self.db.delete(item)
        await self.db.commit()
        return True
'''
        
        service_file = service_dir / "app" / "services" / f"{self.service_name.replace('-', '_')}_service.py"
        service_file.write_text(service_content)
    
    def _create_dockerfile(self, service_dir: Path):
        """创建Dockerfile"""
        dockerfile_content = f'''# RedFire {self.service_title}服务 Docker镜像
FROM python:3.11-slim

WORKDIR /app

# 安装系统依赖
RUN apt-get update && apt-get install -y \\
    gcc \\
    curl \\
    && rm -rf /var/lib/apt/lists/*

# 复制依赖文件
COPY requirements.txt .

# 安装Python依赖
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY app/ app/
COPY tests/ tests/

# 创建日志目录
RUN mkdir -p logs

# 设置环境变量
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1

# 暴露端口
EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \\
    CMD curl -f http://localhost:8000/health || exit 1

# 启动命令
CMD ["python", "app/main.py"]
'''
        
        dockerfile = service_dir / "Dockerfile"
        dockerfile.write_text(dockerfile_content)
    
    def _create_requirements(self, service_dir: Path):
        """创建requirements.txt"""
        requirements_content = '''# RedFire微服务基础依赖
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic==2.5.0
pydantic-settings==2.1.0
sqlalchemy==2.0.23
alembic==1.13.1
asyncpg==0.29.0
redis==5.0.1
python-jose[cryptography]==3.3.0
python-multipart==0.0.6
python-dotenv==1.0.0
httpx==0.25.2

# 日志和监控
structlog==23.2.0
prometheus-client==0.19.0

# 测试依赖
pytest==7.4.3
pytest-asyncio==0.21.1
pytest-cov==4.1.0
'''
        
        requirements_file = service_dir / "requirements.txt"
        requirements_file.write_text(requirements_content)
    
    def _create_readme(self, service_dir: Path):
        """创建README.md"""
        readme_content = f'''# RedFire {self.service_title}服务

基于RedFire统一微服务架构的{self.service_title}服务。

## 功能特性

- ✅ 统一的服务基类
- ✅ 标准化的API接口
- ✅ 统一的配置管理
- ✅ 统一的依赖注入
- ✅ 统一的异常处理
- ✅ 统一的健康检查
- ✅ 统一的日志记录
- ✅ 数据库集成
- ✅ 缓存支持
- ✅ 消息队列集成

## 快速开始

### 本地开发

1. 安装依赖:
```bash
pip install -r requirements.txt
```

2. 启动服务:
```bash
python app/main.py
```

3. 访问API文档:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc

### Docker部署

1. 构建镜像:
```bash
docker build -t redfire-{self.service_name} .
```

2. 运行容器:
```bash
docker run -p 8000:8000 redfire-{self.service_name}
```

## API接口

### 健康检查
- `GET /health` - 服务健康检查

### {self.service_title}管理
- `GET /` - 获取{self.service_title}列表
- `POST /` - 创建{self.service_title}
- `GET /{{id}}` - 获取{self.service_title}详情
- `PUT /{{id}}` - 更新{self.service_title}
- `DELETE /{{id}}` - 删除{self.service_title}

## 配置

服务配置通过RedFire统一配置系统管理，支持:

- 环境变量
- 配置文件
- 动态配置

主要配置项:
- `server.host` - 服务主机 (默认: 0.0.0.0)
- `server.port` - 服务端口 (默认: 8000)
- `debug` - 调试模式 (默认: false)
- `database.*` - 数据库配置
- `redis.*` - Redis配置

## 开发指南

### 目录结构

```
{self.service_name}/
├── app/                    # 应用代码
│   ├── api/               # API路由
│   ├── core/              # 核心逻辑
│   ├── models/            # 数据模型
│   ├── schemas/           # Pydantic模式
│   ├── services/          # 业务服务
│   └── main.py           # 应用入口
├── tests/                 # 测试代码
│   ├── unit/             # 单元测试
│   └── integration/      # 集成测试
├── logs/                  # 日志文件
├── Dockerfile            # Docker配置
├── requirements.txt      # Python依赖
└── README.md            # 项目文档
```

### 添加新功能

1. 在 `models/` 中定义数据模型
2. 在 `schemas/` 中定义请求/响应模式
3. 在 `services/` 中实现业务逻辑
4. 在 `api/` 中添加API路由
5. 编写测试用例

## 测试

运行测试:
```bash
# 所有测试
pytest

# 单元测试
pytest tests/unit/

# 集成测试
pytest tests/integration/

# 测试覆盖率
pytest --cov=app tests/
```

## 部署

### 本地部署
```bash
python app/main.py
```

### Docker部署
```bash
docker build -t redfire-{self.service_name} .
docker run -p 8000:8000 redfire-{self.service_name}
```

### Docker Compose部署
在项目根目录的 `docker-compose.yml` 中已包含此服务配置。

## 监控

- 健康检查端点: `/health`
- Prometheus指标端点: `/metrics` (如果启用)
- 结构化日志输出到 `logs/` 目录

## 贡献

请遵循RedFire开发规范:
1. 使用统一的代码风格
2. 编写完整的测试用例
3. 更新相关文档
4. 提交PR前运行所有测试

## 许可证

MIT License
'''
        
        readme_file = service_dir / "README.md"
        readme_file.write_text(readme_content)
    
    def _show_next_steps(self):
        """显示后续步骤"""
        print("\n📋 后续步骤:")
        print("1. 根据业务需求修改模型和API接口")
        print("2. 实现具体的业务逻辑")
        print("3. 编写测试用例")
        print(f"4. 更新项目根目录的 docker-compose.yml 添加 {self.service_name} 服务配置")
        print("5. 更新API网关路由配置")
        print("6. 更新监控和日志配置")
        print("\n🔗 相关文档:")
        print("- 开发指南: docs/development/")
        print("- API规范: docs/api/")
        print("- 部署指南: docs/deployment/")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="RedFire微服务创建工具")
    
    parser.add_argument(
        'service_name',
        help='微服务名称 (例如: payment-service)'
    )
    
    parser.add_argument(
        '--type', '-t',
        choices=['api', 'websocket', 'worker'],
        default='api',
        help='服务类型 (默认: api)'
    )
    
    args = parser.parse_args()
    
    # 验证服务名称
    if not args.service_name or not args.service_name.replace('-', '').replace('_', '').isalnum():
        print("❌ 错误: 服务名称只能包含字母、数字和连字符")
        return 1
    
    # 创建服务
    creator = ServiceCreator(args.service_name, args.type)
    success = creator.create_service()
    
    return 0 if success else 1


if __name__ == "__main__":
    exit(main())
